package com.scoreMgr.service;

import java.util.Date;

import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.scoreMgr.model.Class;

public class ClassService {

	public static final ClassService me = new ClassService();
	public static final Class dao = new Class().dao();
	
	/**
	 * table分页数据查询
	 * @param page
	 * @param limit
	 * @param keywords
	 * @param 
	 * @return
	 */
	public Page<Class> paginate(int page,int limit, String keywords){
		StringBuilder sb = new StringBuilder();
		if(StrKit.notBlank(keywords)){
			sb.append(" and (class.name like '%"+keywords+"%' or class.grade like '%"+keywords+"%' or class.major like '%"+keywords+"%' "
					+ "or class.num like '%"+keywords+"%' or class.academy like '%"+keywords+"%')");
		}
		if(sb.length() > 0){
			sb.insert(0, "from class where 1=1 ");
			sb.append(" order by class.id desc");
		} else {
			sb.append("from class");
			sb.append(" order by class.id desc");
		}
		return dao.paginate(page, limit, "select id,name,grade,major,num,academy,createTime",sb.toString());
	}
	
	/**
	 * 创建课程
	 * @param clas
	 * @param name
	 * @return ret
	 */
	private Ret create(Class clas, String name) {
		clas.setCreateTime(new Date());
		Class cla =dao.findFirst("select id from class where name='"+name+"'");
		if(cla != null){
			return Ret.fail();
		} else {
			clas.save();
			return Ret.ok();
		}
	}
	
	/**
	 * 
	 * 更新课程信息
	 * @param clas
	 * @return ret
	 */
	private Ret update(Class clas) {
		boolean success = clas.update();
		if(success){
			return Ret.ok();
		} else {
			return Ret.fail();
		}
	}
	
	/**
	 * 提交表单
	 * @param clas
	 * 
	 * @return
	 */
	public Ret submit(Class clas, String name){
		if(clas.getId() == null || clas.getId() <= 0){
			return create(clas,name);
		} else {
			return update(clas);
		}
	}
	
	/**
	 * 根据id删除单条用户信息
	 * @param id
	 * @return  ret
	 */
	public Ret delById(Integer id){
		boolean success = dao.deleteById(id);
		if(success){
			return Ret.ok();
		} else {
			return Ret.fail();
		}
	}
	
}
